<template>
  <view>
    <image ref="lazyImg" id="lazyImg" v-if="curSrc" :src="curSrc" :data-src="src" :style="{width: width, height: height}" :mode="mode" @load="onLoadImg" @error="onErrorImg"></image>
  </view>
</template>
<script>
export default {
  name: 'lazyImg',
  data() {
    return {
      curSrc: '',
      hasError: false
    }
  },
  props:{
    width: String,
    height: String,
    src: String,
    mode: {
      type: String,
      default: 'scaleToFill'
    },
    placehold: {
      type: String,
      default: '/static/img_placehold.png'
    }
  },
  created() {
    this.curSrc = this.placehold
  },
  beforeDestroy() {
    this.hasError = false
  },
  mounted(){
    // let child = this.$refs.lazyImg
    // let observer = new IntersectionObserver(entries => {
    //   entries.forEach(item => {
    //     if(item.isIntersecting){
    //       let imgUrl = item.target.dataset.src
    //       if (imgUrl === '') return
    //       item.target.childNodes[0].style.backgroundImage = `url('${imgUrl}')`
    //       item.target.childNodes[1].src = imgUrl
    //     }
    //   })
    // })
    // observer.observe(child._vnode.elm)
  },
  methods: {
    onLoadImg(e) {
      const imgSrc = e.target.dataset.src
      if (this.hasError) return
      this.curSrc = imgSrc
    },
    onErrorImg(e) {
      // console.log('onError', e)
      this.hasError = true
      this.curSrc = this.placehold
    }
  }
}
</script>

<style lang="less">
</style>